import req from 'request-promise'
import { sortRaw } from './util'
const api = {
  authorize: 'https://open.weixin.qq.com/connect/oauth2/authorize',
  accessToken: 'https://api.weixin.qq.com/sns/oauth2/access_token',
  userInfo: 'https://api.weixin.qq.com/sns/userinfo'
}
export default class wxAuthor {
  constructor(opts) {
    this.appID = opts.appID
    this.appSecret = opts.appSecret
    this.params = sortRaw
  }
  async request(o) {
    o.method = o.method || 'GET'
    let _o = Object.assign({}, o, {json: true})
    if (o.data) {
      let url = o.url + (o.url.indexOf('?') < 0 ? '?' : '&') + this.params(o.data)
      if (o.data._payload) {
        for (let v of o.data._payload) {
          url += v
        }
      }
      _o['url'] = url
      delete _o.data
    }
    try {
      let response = await req(_o)
      return response
    } catch (error) {
      console[!console.error ? 'log' : 'error'](error)
    }
  }
  //  这是从服务端获取AccessToken的函数
  async fetchAccessToken(code) {
    const opt = {
      url: api.accessToken,
      data: {
        appid: this.appID,
        secret: this.appSecret,
        code: code,
        grant_type: 'authorization_code'
      }
    }
    const data = await this.request(opt)
    return data
  }
  toAuthorizeUrl(scope = 'snsapi_base', target, state) {
    return `${api.authorize}?appid=${this.appID}&redirect_uri=${encodeURIComponent(target)}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
  }
  async getUserInfo(token, openid, lang = 'zh_CN') {
    const opt = {
      url: api.userInfo,
      data: {
        access_token: token,
        openid: openid,
        lang: lang
      }
    }
    const data = await this.request(opt)
    return data
  }
}
